<?php namespace App\Http\Controllers\Site;

use App\Http\Requests;
use App\Item;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;

class InfoController extends Controller
{
    public function postUpdate(Request $request, $type, $id = 0)
    {
        $model = Item::findOrNew($id);
        $data = $request->all();
        unset($data['_token']);

        if (!$model->id) {
            $model->user_id = 0;
        }
        if (Cache::has('validator')) {
            $validator = Cache::get('validator');
        } else {
            $validator = [];
        }
        if (!isset($validator[$type])) {
            $tmparry = config('site.items.' . $type);
            $validator[$type]['attributes'] = [];
            $validator[$type]['rules'] = [];
            foreach($tmparry['data'] as $key=>$item){
                if("" != $item['attribute']){
                    $validator[$type]['attributes'][$key]=$item['name'];
                    $validator[$type]['rules'][$key]=$item['attribute'];
                }
            }
            Cache::put('validator',$validator,config('site.cacheTime'));
        }
        $validators = $validator[$type];
        unset($validator);
        $validator = \Validator::make($data, $validators['rules'], ['required' => ':attribute不能为空','email' => ':attribute不是有效的邮箱地址',], $validators['attributes']);
        if ($validator->fails()) {
            $message = $validator->messages();
            $ret['message'] = $message;
            $ret['state'] = 'fail';
            foreach ($validators['attributes'] as $k => $attr) {
                if ($message->has($k)) {
                    $ret['message'] = $message->first($k);
                    break;
                }
            }
        } else {
            $datas['name'] = reset($data);
            $datas['type'] = $type;
            $datas['content'] = json_encode($data);
            if (!$model->id) {
                $model->user_id = 0;
            }
            $datas['kind'] = 0;
            $model->fill($datas);
            $model->save();//写入数据库

            if ($model->id) {
                $ret = ['state' => 'success', 'message' => '我们已经收到您的信息，我们会尽快处理。谢谢！'];
            } else {
                $ret['message'] = '保存出错';
            }
        }
        return \Response::json($ret);
    }
}